package org.leviatan.dataharbour.gui.swingmodels;

import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.leviatan.dataharbour.core.model.HarbourRequest;
import org.leviatan.dataharbour.gui.RuntimeContext;


public class TreeMdlSender extends DefaultTreeModel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2369553015291409622L;

	private DefaultMutableTreeNode theRoot;
	
	private Vector<TreeNodeMdlSender> treeNodeModels;
	

	public TreeMdlSender() {
		super(new DefaultMutableTreeNode("senders"));
		this.theRoot = (DefaultMutableTreeNode) this.getRoot();
		
		this.treeNodeModels = new Vector<TreeNodeMdlSender>();
		this.buildTree();	
	}
	
	public void buildTree() {
		
		Map senders2req = RuntimeContext.dataHarbourService.getAllUnpersistedHarbourRequests();
		
		//DataHarbourServiceProxy proxy = RuntimeContext.dataHarbourService;
		
		
		TreeNodeMdlSender nodeMdlSender;
		TreeNodeMdlHarbourRequest nodeMdlRequest;
		
		
		// iterate senders
		for (Iterator i = senders2req.keySet().iterator(); i.hasNext(); ) {
			String senderId = i.next().toString();
			
		
			nodeMdlSender = new TreeNodeMdlSender(senderId);
			this.theRoot.add(nodeMdlSender);
			this.treeNodeModels.addElement(nodeMdlSender);
			
			// get corr. requests
			Vector sendersReqs = (Vector) senders2req.get(senderId);
			if (sendersReqs == null || sendersReqs.isEmpty()) break;
			
			HarbourRequest aReq;
			// and iterate those
			for(Iterator j = sendersReqs.iterator(); j.hasNext(); ) {
				
				aReq = (HarbourRequest) j.next();
				
				nodeMdlRequest = new TreeNodeMdlHarbourRequest(aReq);
				nodeMdlSender.add(nodeMdlRequest);
				
			}
		}
	}
		
	
	
	public void reload() {
		this.theRoot.removeAllChildren();
		this.buildTree();
		super.reload();
	}

	public DefaultMutableTreeNode getTheRoot() {
		return theRoot;
	}

	public void setTheRoot(DefaultMutableTreeNode theRoot) {
		this.theRoot = theRoot;
	}
	

}
